package com.asr.testclient.view;

import javax.swing.*;
import java.awt.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 结果显示面板
 * 显示识别结果和错误信息
 */
public class ResultPanel extends JPanel {
    private JTextArea resultTextArea;
    private JButton clearResultButton;
    private JScrollPane scrollPane;
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public ResultPanel() {
        initComponents();
        layoutComponents();
    }

    private void initComponents() {
        resultTextArea = new JTextArea(8, 50);
        resultTextArea.setEditable(false);
        resultTextArea.setLineWrap(true);
        resultTextArea.setWrapStyleWord(true);
        scrollPane = new JScrollPane(resultTextArea);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        
        clearResultButton = new JButton("清空结果");
    }

    private void layoutComponents() {
        setLayout(new BorderLayout(5, 5));
        setBorder(BorderFactory.createTitledBorder("识别结果"));

        // 结果文本区域
        add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        buttonPanel.add(clearResultButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    /**
     * 追加识别结果
     */
    public void appendResult(String result) {
        String timestamp = LocalDateTime.now().format(TIME_FORMATTER);
        String message = String.format("[%s] 识别结果: %s\n", timestamp, result);
        resultTextArea.append(message);
        resultTextArea.setCaretPosition(resultTextArea.getDocument().getLength());
    }

    /**
     * 追加错误信息
     */
    public void appendError(String error) {
        String timestamp = LocalDateTime.now().format(TIME_FORMATTER);
        String message = String.format("[%s] [错误] %s\n", timestamp, error);
        resultTextArea.append(message);
        resultTextArea.setCaretPosition(resultTextArea.getDocument().getLength());
    }

    /**
     * 清空结果
     */
    public void clearResults() {
        resultTextArea.setText("");
    }

    /**
     * 设置状态信息
     */
    public void setStatus(String status) {
        String timestamp = LocalDateTime.now().format(TIME_FORMATTER);
        String message = String.format("[%s] %s\n", timestamp, status);
        resultTextArea.append(message);
        resultTextArea.setCaretPosition(resultTextArea.getDocument().getLength());
    }

    /**
     * 获取清空结果按钮
     */
    public JButton getClearResultButton() {
        return clearResultButton;
    }
}
